from PyQt5.QtWidgets import QTableWidget, QTableWidgetItem, QVBoxLayout, QWidget, QCheckBox

"""
    [{
        "url": "https://yktnews.com",
        "html_tag": [
            {"key": "title","x_path": "//*[@id=\"tdi_69\"]/div/div/div[1]/h2/a", "is_attr": "" },
            {"key": "link","x_path": "//*[@id=\"tdi_69\"]/div/div/div[1]/h2/a","is_attr": "href"}
        ],
        "encode": "iso-8859-1",
        "decode": "utf-8"
    }]
"""


class TableWithDataList(QWidget):
    def __init__(self, store):
        super().__init__()
        self.store = store
        self.initUI()

    def initUI(self):
        # 创建一个垂直布局
        layout = QVBoxLayout()

        # 创建一个表格
        self.table = QTableWidget(0, 3)  # 创建一个0行3列的表格
        self.table.setHorizontalHeaderLabels(['名称', '网址', '抓取开关'])

        web_list = self.store.dispatch("get_web_table")
        # 填充表格数据
        for i, web in enumerate(web_list):
            key = web["key"]
            url = web["url"]
            start = web["start"]
            self.table.insertRow(i)
            self.table.setItem(i, 0, QTableWidgetItem(key))
            self.table.setItem(i, 1, QTableWidgetItem(url))

            # 创建一个复选框，并将其添加到表格的最后一列
            checkbox = QCheckBox()
            checkbox.setChecked(start == 1)
            checkbox.stateChanged.connect(lambda state, row=i: self.update_checkbox_state(row))
            self.table.setCellWidget(i, 2, checkbox)

        # 设置列宽
        self.table.setColumnWidth(1, 300)  # 设置第二列（URL列）的宽度

        # 将表格添加到布局
        layout.addWidget(self.table)

        # 设置布局
        self.setLayout(layout)

    """
        触发数据更新
    """

    def update_checkbox_state(self, row):
        checkbox_widget = self.table.cellWidget(row, 2)
        # 获取当前行第 0 列的项
        key_item = self.table.item(row, 0)
        key = key_item.text() if key_item else None
        if isinstance(checkbox_widget, QCheckBox) and checkbox_widget.isChecked():
            print(f"选中{key}")
            self.store.commit("update_web_table_by_key", key, {'start': 1})
        else:
            print(f"取消{key}")
            self.store.commit("update_web_table_by_key", key, {'start': 0})
